# coding: utf8

import tornado.web
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
import logging as log

from tornado.escape import json_decode, to_unicode

from libs import myjson as json

log.basicConfig(format='[%(asctime)s] [%(filename)s]:[line:%(lineno)d] [%(levelname)s] %(message)s', level=log.INFO)


class BaseController(tornado.web.RequestHandler):

    def data_received(self, chunk):
        pass

    def render_json(self, code=0, msg='', data=None):
        data = data or {}
        json_relt = json.dumps({'code': code, 'msg': msg, 'data': data})

        callback = self.get_argument('callback', '', True)
        if callback:
            json_relt = '%s(%s)' % (callback, json_relt)
        return self.finish(json_relt)

    def pagination(self, object_list, number_per_page=10, page_num=-1, photo_style=''):

        records_total = object_list.count()
        if page_num <= 0: page_num = self.int_argument('pageNum', 0)
        if page_num <= 0: page_num = 1
        paginator = Paginator(object_list, number_per_page)
        try:
            # log.info('normal')
            pagination_objects = paginator.page(page_num)
        except PageNotAnInteger:
            # log.info('PageNotAnInteger')
            pagination_objects = paginator.page(1)  # If page is not an integer, deliver first page.
        except EmptyPage:
            # log.info('EmptyPage')
            pagination_objects = paginator.page(
                paginator.num_pages)  # If page is out of range (e.g. 9999), deliver last page of results.
            pagination_objects.object_list = []

        return dict(
            pageNum=pagination_objects.number,
            pageSize=number_per_page,
            pageTotal=pagination_objects.paginator.num_pages,
            recordsTotal=records_total,

            # page_num=pagination_objects.number,
            # page_size=number_per_page,
            # page_total=pagination_objects.paginator.num_pages,
            # records_total=records_total,
            records=[obj.to_dict(photo_style) for obj in pagination_objects.object_list] if pagination_objects.object_list else [])

    def pagination_list(self, object_list, number_per_page=10, page_num=-1):

        records_total = len(object_list)
        if page_num <= 0: page_num = self.int_argument('pageNum', 0)
        if page_num <= 0: page_num = 1
        paginator = Paginator(object_list, number_per_page)
        try:
            # log.info('normal')
            pagination_objects = paginator.page(page_num)
        except PageNotAnInteger:
            # log.info('PageNotAnInteger')
            pagination_objects = paginator.page(1)  # If page is not an integer, deliver first page.
        except EmptyPage:
            # log.info('EmptyPage')
            pagination_objects = paginator.page(
                paginator.num_pages)  # If page is out of range (e.g. 9999), deliver last page of results.
            pagination_objects.object_list = []

        return dict(
            pageNum=pagination_objects.number,
            pageSize=number_per_page,
            pageTotal=pagination_objects.paginator.num_pages,
            recordsTotal=records_total,

            # page_num=pagination_objects.number,
            # page_size=number_per_page,
            # page_total=pagination_objects.paginator.num_pages,
            # records_total=records_total,
            records=pagination_objects.object_list)

    def get_json_argument(self, name, default=None):

        args = json_decode(self.request.body)
        name = to_unicode(name)
        if name in args:
            return args[name]
        elif default is not None:
            return default
        else:
            return None

    def int_argument(self, k, default=0):
        v = self.get_argument(k, default)
        try:
            return int(v)
        except:
            return default
